<template>
  <a-row :gutter="0">
    <a-col :md="24">
      <a-card :style="cardStyle" :bordered="false">
        <!-- 查询区域 -->
        <div class="table-page-search-wrapper" v-if="showSearch">
          <!-- 搜索区域 -->
          <a-form :form="searchForm" layout="inline" @keyup.enter.native="searchQuery">
            <a-row :gutter="24">
              <template v-if="columns">
                <a-col :md="24/rowColumnCount" :sm="24" v-for="(item,index) in searchColumns" v-if="index < rowColumnCount - 1">
                  <form-editor :item="item" :dictValues="dictValues" :key="index" opType="search" :formModel="queryParam"></form-editor>
                </a-col>
              </template>
              <template v-if="toggleSearchStatus && searchColumns.length >= rowColumnCount - 1">
                <a-col :md="24/rowColumnCount" :sm="24" v-for="(item,index) in searchColumns" v-if="index >= rowColumnCount - 1">
                  <form-editor :item="item" :dictValues="dictValues" :key="index" opType="search" :formModel="queryParam"></form-editor>
                </a-col>
              </template>
              <span style="float: left;overflow: hidden;" class="table-page-search-submitButtons">
                <a-col :md="24/rowColumnCount" :sm="24">
                  <a-button type="primary" @click="searchQuery">查询</a-button>
                  <a-button style="margin-left: 8px" @click="searchReset">重置</a-button>
                  <a @click="handleToggleSearch" style="margin-left: 8px" v-if="searchColumns.length >= rowColumnCount">
                    {{ toggleSearchStatus ? '收起' : '展开' }}
                    <a-icon :type="toggleSearchStatus ? 'up' : 'down'" />
                  </a>
                </a-col>
              </span>
            </a-row>
          </a-form>
        </div>
        <!-- 操作按钮区域 -->
        <div class="table-operator" style="margin-top: 5px">
          <template v-for="(btn,index) in topButtons">
            <a-upload v-if="btn.name == 'import'" name="file" :showUploadList="false" :multiple="false" :headers="tokenHeader"
              :action="importExcelUrl" @change="handleImportExcel">
              <a-popover title="表格模板">
                <template slot="content">
                  <p><a target="_blank" :href="importTemplateUrl"><b>下载模板</b></a></p>
                </template>
                <a-button :icon="btn.icon">{{btn.title}}</a-button>
              </a-popover>
            </a-upload>
            <a-button v-else-if="btn.name == 'printTable'" :icon="btn.icon" @click="handleExportXls('导出数据')">{{btn.title}}</a-button>
            <a-button v-else-if="btn.name == 'export'" :icon="btn.icon" @click="handleExportXls('导出数据')">{{btn.title}}</a-button>
            <a-button v-else @click="handleButton(btn)" :type="randerButton(btn)" :icon="btn.icon" :class="btn.class">{{ btn.title }}</a-button>
          </template>
        </div>
        <!-- table区域-begin -->
        <div>
          <a-table ref="table" size="middle" bordered :rowKey="rowKey" :columns="tableColumns" :dataSource="dataSource"
            :pagination="ipagination" :scroll="scroll" :loading="loading"
            :rowSelection="{selectedRowKeys: selectedRowKeys, onChange: onSelectChange}" @change="handleTableChange">
            <span slot="action" slot-scope="text, record">
              <template v-for="(btn, index) in inlineButtons">
                <a-divider v-if="inlineButtons.length > 1 && index > 0" type="vertical" />
                <a-popconfirm v-if="btn.name =='delete'" :title="'确定' + btn.title + '吗?'" @confirm="() => handleButton(btn, record.id)">
                  <a>{{btn.title}}</a>
                </a-popconfirm>
                <a v-else @click="handleButton(btn, record)">{{btn.title}}</a>
              </template>
              <template v-for="(page, index) in subPages">
                <a-divider type="vertical" />
                  <a @click="handleSubPage(page, record)">{{page.title}}</a>
              </template>
            </span>
            <template slot="customRenderSwitcher" slot-scope="yesOrNo">
              <a-tag v-if="yesOrNo==1" color="green">是</a-tag>
              <a-tag v-if="yesOrNo==0" color="orange">否</a-tag>
            </template>
          </a-table>
        </div>
        <!-- table区域-end -->
        <!-- 表单区域 -->
        <simple-edit-modal ref="modalForm" @ok="modalFormOk" :columns="modalColumns" :dictValues="dictValues" :agilePageCode="agilePageCode"></simple-edit-modal>
        <simple-detail-modal ref="modalDetail" :columns="modalColumns" :dictValues="dictValues"></simple-detail-modal>
        <modal-page ref="modalPage" :template="modalPageData.template" :title="modalPageData.title" :queryParam="modalPageData.queryParam"  :agilePageCode="modalPageData.agilePageCode"></modal-page>
      </a-card>
    </a-col>
  </a-row>
</template>
<script>
  import SimpleEditModal from './modal/SimpleEditModal'
  import SimpleDetailModal from './modal/SimpleDetailModal'
  import ModalPage from './modal/ModalPage'
  import FormEditor from './modal/FormEditor'
  import {
    queryMaterialCategoryTreeList
  } from '@/api/api'
  import {
    postAction
  } from '@/api/manage'
  import {
    getMpListShort
  } from "@/utils/util"
  import {
    JTableListMixin
  } from '@/mixins/JTableListMixin'
  import { agileTemplate } from '@/api/api'
  import JDate from '@/components/jeecg/JDate'
  import Vue from 'vue'
  export default {
    name: "SimpleTable",
    mixins: [JTableListMixin],
    components: {      
      FormEditor,
      SimpleEditModal,
      SimpleDetailModal,
      ModalPage,
      JDate
    },
    props: {
      agilePageCode: {
        type: String,
        required: true
      },
      pagination: {
        type: Object,
        required: false
      },
      columns: {
        type: Array,
        required: true,
        default(){
          return []
        }
      },
      dictValues: {
        type: Object,
        required: false,
        default(){
          return {}
        }
      },
      url: {
        type: Object,
        required: false,
        default(){
          return {}
        }
      },
      pageSize: {
        type: Number,
        default: 10
      },
      pageNum: {
        type: Number,
        default: 1
      },
      pageSizeOptions: {
        type: Array,
        default () {
          return ['10', '20', '30', '50', '100']
        }
      },      
      rowColumnCount: {
        type: Number,
        required: false,
        default: 3
      },
      responseParamsName: {
        type: Object,
        default () {
          return {}
        }
      },
      bordered: {
        type: Boolean,
        default: false
      },
      /**
       * 表格大小风格，default, middle, small
       */
      size: {
        type: String,
        default: 'default'
      },
      rowKey: {
        type: String,
        default: 'id'
      },
      subPages: {
        type: Array,
        required: false,
        default () {
          return []
        }
      },
      showSearch: {
        type: Boolean,
        required: false,
        default (){
          return true;
        }
      },
      // 查询条件
      queryParam: {},
      buttons: {
        type: Array,
        required: false,
        default () {
          return [{
              "name": "add",
              "title": "新增",
              "icon":"plus"
            },
            {
              "name": "copy",
              "title": "复制",
            },
            {
              "name": "import",
              "title": "导入",
              "icon":"import"
            },
            {
              "name": "export",
              "title": "导出",
              "icon":"download"
            },
            {
              "name": "batchDelete",
              "title": "删除",
              "icon":"delete"
            },
            {
              "name": "edit",
              "title": "编辑",
              "icon":"edit",
              "buttonType": "inline"
            },
            {
              "name": "delete",
              "title": "删除",
              "icon": "danger",
              "buttonType": "inline"
            },            
            {
              "name": "detail",
              "title": "详情",
              "buttonType": "inline"
            },
            {
              "name": "printTable",
              "title": "打印",
              "icon": "printer"
            },
            {
              "name": "reload",
              "title": "刷新",
              "icon":"reload",
              "class": "pull-right"
            },
          ]
        }
      }
    },
    data() {
      return {
        categoryTree: [],
        mPropertyListShort: '',
        model: {},
        modalPageData: {
          template: "SimplateTablePage",
          agilePageCode: ''
        },
        labelCol: {
          span: 5
        },
        wrapperCol: {
          span: 18,
          offset: 1
        },
        searchForm: this.$form.createForm(this)
      }
    },
    created() {
      this.model = Object.assign({}, {});
    },
    computed: {
      searchColumns() {
        var params = []
        for (var idx in this.columns) {
          const c = this.columns[idx]
          if (c.searchable) {
            params.push(c)
          }
        }
        return params
      },
      inlineButtons(){
        var btns = [];
        for (var idx in this.buttons) {
          const c = this.buttons[idx]
          if(c.buttonType == 'inline'){
            btns.push(c)
          }
        }
        return btns;
      },
      topButtons(){
        var btns = [];
        for (var idx in this.buttons) {
          const c = this.buttons[idx]
          if(c.buttonType != 'inline'){
            btns.push(c)
          }
        }
        return btns;
      },
      tableColumns() {
        var params = []
        var that = this;
        for (var idx in this.columns) {
          const c = this.columns[idx]
          const d = Object.assign({}, c);
          d["title"] = c["label"]
          d["dataIndex"] = c["fieldName"]
          if(c.dataSourceType == 'TABLE_COLUMN' || c.dataSourceType == 'DICT' || c.dataSourceType == 'ENUM'){
            d["customRender"] = function (text) {
              const param = c.dataSourceTypeParam;
              const ps = param.split(".");
			  if(ps.length <= 3){
				return that.getDictValue(ps[0], text)
			  }else{
				  return that.getDictValue(param, text)
			  }
            }
          }else if(c.editorType == 'YES_OR_NO' || c.dataType == 'BOOLEAN'){
            d["scopedSlots"] = {customRender: "customRenderSwitcher"};
          }else if(c.dataType == 'DECIMAL'){
            d["customRender"] = function (text) {
                text = text + '';
                const ss = text.split(".");
                const scale = ss[1]
                const w = [];
                const len = ss[0].length;
                var idx = 0;
                for(var l in [16, 12, 8, 4]){
                  if(len > l){
                    w.push(ss.substr(idx, len-l));
                    w.push("_")
                    idx = len-l
                    len = l
                  }
                }
                w.push(ss.substr(idx, len))
                return w.join("")
            }
          }
          params.push(d)
        }
        var found = false;
        for(var idx in params){
          const p = params[idx];
          if(p.dataIndex == 'action'){
            found = true;
            break;
          }          
        }
        if(!found){
          params.push({
            title: '操作',
            dataIndex: 'action',
            align:"center",
            width: ((this.inlineButtons.length  * 50) +  (this.subPages.length * 80) ) + "px",
            scopedSlots: { customRender: 'action' },
          })
        }
        return params
      },
      modalColumns() {
        var params = []
        for (var idx in this.columns) {
          const c = this.columns[idx]
          const d = Object.assign({}, c);
          d["title"] = c["label"]
          d["dataIndex"] = c["fieldName"]
          params.push(d)
        }
        return params;
      },
      importTemplateUrl: function() {
        if(this.url && this.url.importExcelUrl){
           return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`;
        }else{
          var pg = {}
          pg["agilePageCode"] = this.agilePageCode;
          return agileTemplate.getImportTemplateUrl(pg);
        }
      },
      importExcelUrl: function() {
        if(this.url && this.url.importExcelUrl){
           return `${window._CONFIG['domianURL']}${this.url.importExcelUrl}`;
        }else{
          var pg = {}
          pg["agilePageCode"] = this.agilePageCode;
          return agileTemplate.getImportExcelUrl(pg);
        }
      }
    },
    methods: {
      getDictValues(field){
        if(field.dataSourceType == 'DICT' || field.dataSourceType == 'ENUM' || field.dataSourceType == 'TABLE_COLUMN'){
          const ss = field.dataSourceTypeParam.split(".");
          if(ss.length <= 3){
            return this.dictValues[ss[0]];
          }else{
            return this.dictValues[field.dataSourceTypeParam];
		  }
        }
      },
      getDictValue(dict, text){
        if(!text){return;}
        text = text + "";
        const vs = this.dictValues[dict];
        if(vs){
          for(var v =0; v < vs.length; v++){
            if(vs[v].valueCode == text){
              return vs[v].valueName;
            }
          }
        }
      },
      calcScale(scale){
        var d = 1;
        if(scale > 0){
          for(var i=0;i<scale; i++){
            d = d/10;
          }
        }else if(scale < 0){
          scale = scale * 1;
          for(var i=0; i<scale; i++){
            d = d * 10;
          }
        }
        return d;
      },
      randerButton(btn){
          switch(btn.name){
            case "batchDelete":
            case "delete":
              return "danger";
            case "add":
              return "primary";
            case "import":
              return "info";
            case "export":
              return "warning";
            default:
              return '';
          }
      },
      handleButton(btn, data) {
        const methods = this.$options.methods;
        const method = 'handle'+ btn.name.charAt(0).toUpperCase() + btn.name.substr(1)
        if(methods[method]){
          methods[method].call(this, data)
        }
      },
      handleSubPage(page, data){
        const url = "/template/"+ page.template + "/" + page.agilePageCode;  
        var params = {}
        params[page.foreignKeyName] = data[page.referenceKeyName];        
        var mp = Object.assign({}, page)
        mp["queryParam"] = params;
        this.modalPageData = mp;
        this.$nextTick(() => {
          this.$refs.modalPage.show(mp);
        });
        window.printLog("show pages:" + url + ",params:" + JSON.stringify(params))      
      },
      
    }
  }
</script>
<style scoped>
  @import '~@assets/less/common.less'
</style>
